import _ from "lodash";

class Drap {
  constructor(el, option = { parent: null }) {
    this.el = el;
    this.el.style.position = "absolute";
    this.el.style.zIndex = 999;
    this.x = 0;
    this.y = 0;
    // 父容器
    if (option?.parent) {
      this.container = document.getElementById(option.parent);
    } else {
      this.container = el.parentNode;
    }
    this.init();
  }
  init() {
    this.el.onmousedown = (e) => {
      e.stopPropagation();
      this.el.style.cursor = "move";
      this.lastLeft = this.el.offsetLeft;
      this.lastTop = this.el.offsetTop;
      this.x = e.clientX;
      this.y = e.clientY;

      this.container.onmousemove = (e) => {
        e.stopPropagation();
        e.preventDefault();
        const offsetX = e.clientX - this.x;
        let left = this.lastLeft + offsetX;
        if (offsetX < 0) {
          // 向左滑动
          if (left < 0) {
            left = 0;
          }
        } else {
          // 向右滑动
          if (left > this.container.offsetWidth - this.el.offsetWidth) {
            left = this.container.offsetWidth - this.el.offsetWidth;
          }
        }

        const offsetY = e.clientY - this.y;
        let top = this.lastTop + offsetY;
        if (offsetY < 0) {
          // 向上滑动
          if (top < 0) {
            top = 0;
          }
        } else {
          // 向下滑动
          if (top > this.container.offsetHeight - this.el.offsetHeight) {
            top = this.container.offsetHeight - this.el.offsetHeight;
          }
        }

        this.el.style.left = left + "px";
        this.el.style.top = top + "px";
      };

      document.onmouseup = (e) => {
        this.container.onmousemove = null;
        document.onmouseup = null;
        this.el.style.cursor = "pointer";
      };
    };
  }
}

export const drag = {
  mounted(el, binding) {
    new Drap(el, binding.value || {});
  },
};
